'use strict';

const Controller = require('egg').Controller;

class JobController extends Controller {
  // 获取岗位列表（多维度筛选 + 关键词搜索）
  async getJobList() {
    const { ctx } = this;
    const { 
      keyword, 
      status, 
      category, 
      location,
      enterpriseId,
      title,
      page = 1, 
      pageSize = 12 
    } = ctx.query;
    
    try {
      const result = await ctx.service.job1.job.getJobList({
        keyword: keyword || title, // 支持 title 参数
        status,
        category,
        location,
        enterpriseId,
        page: parseInt(page),
        pageSize: parseInt(pageSize)
      });
      
      // 映射字段名以匹配前端
      const mappedData = (result.list || []).map(job => {
        const jobData = job.toJSON ? job.toJSON() : job;
        return {
          ...jobData,
          title: jobData.jobName,
          status: jobData.jobStatus,
          enterpriseName: jobData.enterprise?.enterpriseName || '未知企业'
        };
      });
      
      ctx.body = {
        code: 0,
        message: '获取成功',
        data: {
          list: mappedData,
          total: result.total || 0,
          pagination: {
            current: result.page || parseInt(page),
            pageSize: result.pageSize || parseInt(pageSize),
            total: result.total || 0,
            pages: Math.ceil((result.total || 0) / parseInt(pageSize))
          }
        }
      };
    } catch (error) {
      ctx.body = {
        code: 500,
        message: error.message || '获取岗位列表失败',
        data: null
      };
    }
  }

  // 获取岗位详情
  async getJobDetail() {
    const { ctx } = this;
    const { jobId } = ctx.params;
    
    try {
      const job = await ctx.service.job1.job.getJobDetail(jobId);
      ctx.body = {
        code: 0,
        data: job,
        msg: '获取成功'
      };
    } catch (error) {
      ctx.body = {
        code: 500,
        data: null,
        msg: error.message || '获取岗位详情失败'
      };
    }
  }

  // 创建岗位
  async createJob() {
    const { ctx } = this;
    const jobData = ctx.request.body;
    
    try {
      const result = await ctx.service.job1.job.createJob(jobData);
      ctx.body = {
        code: 0,
        data: result,
        msg: '创建成功'
      };
    } catch (error) {
      ctx.body = {
        code: 500,
        data: null,
        msg: error.message || '创建岗位失败'
      };
    }
  }

  // 更新岗位
  async updateJob() {
    const { ctx } = this;
    const { jobId } = ctx.params;
    const updateData = ctx.request.body;
    
    try {
      const result = await ctx.service.job1.job.updateJob(jobId, updateData);
      ctx.body = {
        code: 0,
        data: result,
        msg: '更新成功'
      };
    } catch (error) {
      ctx.body = {
        code: 500,
        data: null,
        msg: error.message || '更新岗位失败'
      };
    }
  }

  // 删除岗位
  async deleteJob() {
    const { ctx } = this;
    const { jobId } = ctx.params;
    
    try {
      await ctx.service.job1.job.deleteJob(jobId);
      ctx.body = {
        code: 200,
        message: '删除成功',
        data: null
      };
    } catch (error) {
      ctx.body = {
        code: 500,
        message: error.message || '删除岗位失败',
        data: null
      };
    }
  }

  // 更新岗位状态（上线/下线）
  async updateJobStatus() {
    const { ctx } = this;
    const { jobId } = ctx.params;
    const { status } = ctx.request.body;
    
    try {
      const result = await ctx.service.job1.job.updateJobStatus(jobId, status);
      ctx.body = {
        code: 0,
        data: result,
        msg: '状态更新成功'
      };
    } catch (error) {
      ctx.body = {
        code: 500,
        data: null,
        msg: error.message || '状态更新失败'
      };
    }
  }

  // 更新岗位置顶状态
  async updateJobTopStatus() {
    const { ctx } = this;
    const { jobId } = ctx.params;
    const { isTop } = ctx.request.body;
    
    try {
      const result = await ctx.service.job1.job.updateJobTopStatus(jobId, isTop);
      ctx.body = {
        code: 0,
        data: result,
        msg: '置顶状态更新成功'
      };
    } catch (error) {
      ctx.body = {
        code: 500,
        data: null,
        msg: error.message || '置顶状态更新失败'
      };
    }
  }

  // 获取岗位投递数据
  async getJobApplicationData() {
    const { ctx } = this;
    const { jobId } = ctx.params;
    
    try {
      const result = await ctx.service.job1.job.getJobApplicationData(jobId);
      ctx.body = {
        code: 0,
        data: result,
        msg: '获取成功'
      };
    } catch (error) {
      ctx.body = {
        code: 500,
        data: null,
        msg: error.message || '获取投递数据失败'
      };
    }
  }

  // 投递岗位
  async applyJob() {
    const { ctx } = this;
    const { jobId } = ctx.params;
    const applicationData = ctx.request.body;
    
    // 验证用户登录
    if (!ctx.user || !ctx.user.id) {
      ctx.body = {
        code: 401,
        data: null,
        msg: '未登录，请先登录'
      };
      return;
    }

    // 获取用户信息
    const userId = ctx.user.id;
    const username = ctx.user.username;
    
    try {
      const result = await ctx.service.job1.job.applyJob(jobId, applicationData, userId, username);
      ctx.body = {
        code: 0,
        data: result,
        msg: '投递成功'
      };
    } catch (error) {
      ctx.body = {
        code: 500,
        data: null,
        msg: error.message || '投递失败'
      };
    }
  }

  // 收藏岗位
  // 收藏岗位
  async collectJob() {
    const { ctx } = this;
    const { jobId } = ctx.params;
    
    // 从 JWT token 中获取用户ID
    const userId = ctx.user?.id;
    
    if (!userId) {
      ctx.body = {
        code: 1,
        data: null,
        msg: '未登录'
      };
      return;
    }
    
    try {
      const result = await ctx.service.job1.job.collectJob(jobId, userId);
      ctx.body = {
        code: 0,
        data: result,
        msg: result.message || '收藏成功'
      };
    } catch (error) {
      ctx.body = {
        code: 500,
        data: null,
        msg: error.message || '收藏失败'
      };
    }
  }

  // 取消收藏岗位
  async uncollectJob() {
    const { ctx } = this;
    const { jobId } = ctx.params;
    
    // 从 JWT token 中获取用户ID
    const userId = ctx.user?.id;
    
    if (!userId) {
      ctx.body = {
        code: 1,
        data: null,
        msg: '未登录'
      };
      return;
    }
    
    try {
      const result = await ctx.service.job1.job.uncollectJob(jobId, userId);
      ctx.body = {
        code: 0,
        data: result,
        msg: result.message || '取消收藏成功'
      };
    } catch (error) {
      ctx.body = {
        code: 500,
        data: null,
        msg: error.message || '取消收藏失败'
      };
    }
  }

  // 获取用户收藏的岗位列表
  async getUserFavoriteJobs() {
    const { ctx } = this;
    const { page = 1, pageSize = 20 } = ctx.query;
    
    // 从 JWT token 中获取用户ID
    const userId = ctx.user?.id;
    
    if (!userId) {
      ctx.body = {
        code: 1,
        data: null,
        msg: '未登录'
      };
      return;
    }
    
    try {
      const result = await ctx.service.job1.job.getUserFavoriteJobs({
        userId,
        page: parseInt(page),
        pageSize: parseInt(pageSize)
      });
      ctx.body = {
        code: 0,
        data: result,
        msg: '获取成功'
      };
    } catch (error) {
      ctx.body = {
        code: 500,
        data: null,
        msg: error.message || '获取收藏列表失败'
      };
    }
  }

  // 检查岗位是否已收藏
  async checkJobCollected() {
    const { ctx } = this;
    const { jobId } = ctx.params;
    
    // 从 JWT token 中获取用户ID
    const userId = ctx.user?.id;
    
    if (!userId) {
      ctx.body = {
        code: 1,
        data: { collected: false },
        msg: '未登录'
      };
      return;
    }
    
    try {
      const result = await ctx.service.job1.job.checkJobCollected(jobId, userId);
      ctx.body = {
        code: 0,
        data: result,
        msg: '查询成功'
      };
    } catch (error) {
      ctx.body = {
        code: 500,
        data: { collected: false },
        msg: error.message || '查询失败'
      };
    }
  }

  // 获取用户投递记录
  async getUserApplications() {
    const { ctx } = this;
    const { status, page = 1, pageSize = 10 } = ctx.query;
    
    // 优先从 JWT token 中获取用户ID，如果没有则从查询参数获取
    const userId = ctx.user?.id || ctx.query.userId;
    
    if (!userId) {
      ctx.body = {
        code: 1,
        data: null,
        msg: '未登录或用户ID无效'
      };
      return;
    }
    
    try {
      const result = await ctx.service.job1.job.getUserApplications({
        userId,
        status,
        page: parseInt(page),
        pageSize: parseInt(pageSize)
      });
      ctx.body = {
        code: 0,
        data: result,
        msg: '获取成功'
      };
    } catch (error) {
      ctx.body = {
        code: 500,
        data: null,
        msg: error.message || '获取投递记录失败'
      };
    }
  }

  // 获取企业的投递记录
  async getEnterpriseApplications() {
    const { ctx } = this;
    const { enterpriseId } = ctx.params;
    const { status, page = 1, pageSize = 100 } = ctx.query;
    
    try {
      const result = await ctx.service.job1.job.getEnterpriseApplications({
        enterpriseId,
        status,
        page: parseInt(page),
        pageSize: parseInt(pageSize)
      });
      ctx.body = {
        code: 0,
        data: result,
        msg: '获取成功'
      };
    } catch (error) {
      ctx.body = {
        code: 500,
        data: null,
        msg: error.message || '获取企业投递记录失败'
      };
    }
  }

  // 撤回投递
  async withdrawApplication() {
    const { ctx } = this;
    const { applicationId } = ctx.params;
    
    try {
      const result = await ctx.service.job1.job.withdrawApplication(applicationId);
      ctx.body = {
        code: 0,
        data: result,
        msg: '撤回成功'
      };
    } catch (error) {
      ctx.body = {
        code: 500,
        data: null,
        msg: error.message || '撤回投递失败'
      };
    }
  }

  // 更新投递状态
  async updateApplicationStatus() {
    const { ctx } = this;
    const { applicationId } = ctx.params;
    const { status } = ctx.request.body;
    
    try {
      const result = await ctx.service.job1.job.updateApplicationStatus(applicationId, status);
      ctx.body = {
        code: 0,
        data: result,
        msg: '状态更新成功'
      };
    } catch (error) {
      ctx.body = {
        code: 500,
        data: null,
        msg: error.message || '状态更新失败'
      };
    }
  }

  // 批量操作岗位
  async batchOperateJobs() {
    const { ctx } = this;
    const { jobIds, operation } = ctx.request.body;
    
    try {
      const result = await ctx.service.job1.job.batchOperateJobs(jobIds, operation);
      ctx.body = {
        code: 0,
        data: result,
        msg: '批量操作成功'
      };
    } catch (error) {
      ctx.body = {
        code: 500,
        data: null,
        msg: error.message || '批量操作失败'
      };
    }
  }

  // 获取所有投递记录（管理员）
  async getAllApplications() {
    const { ctx } = this;
    const { page = 1, pageSize = 10, status } = ctx.query;

    try {
      const where = {};
      if (status) {
        where.status = status;
      }

      const { count, rows } = await ctx.model.JobApplication.findAndCountAll({
        where,
        limit: parseInt(pageSize),
        offset: (parseInt(page) - 1) * parseInt(pageSize),
        order: [['applyTime', 'DESC']],
        include: [
          {
            model: ctx.model.Job,
            as: 'job',
            attributes: ['jobId', 'jobName', 'salary', 'location'],
            include: [{
              model: ctx.model.Enterprise,
              as: 'enterprise',
              attributes: ['enterpriseId', 'enterpriseName']
            }]
          },
          {
            model: ctx.model.User,
            as: 'user',
            attributes: ['id', 'username', 'email']
          },
          {
            model: ctx.model.Resume,
            as: 'resume',
            attributes: ['id', 'resume_name']
          }
        ]
      });

      const processedRows = rows.map(row => {
        const data = row.toJSON();
        data.jobTitle = data.job ? data.job.jobName : '未知岗位';
        data.enterpriseName = data.job && data.job.enterprise ? data.job.enterprise.enterpriseName : '未知企业';
        data.username = data.user ? data.user.username : `用户${data.userId}`;
        data.resumeName = data.resume ? data.resume.resume_name : '在线简历';
        return data;
      });

      ctx.body = {
        code: 200,
        message: '获取成功',
        data: processedRows,
        pagination: {
          current: parseInt(page),
          pageSize: parseInt(pageSize),
          total: count,
          pages: Math.ceil(count / parseInt(pageSize))
        }
      };
    } catch (error) {
      ctx.body = {
        code: 500,
        message: '获取投递记录失败: ' + error.message,
        data: null
      };
    }
  }
}

module.exports = JobController;










































